//
//  LinePointDetailView.m
//  BezierPathDraw
//
//  Created by huyuchen on 2018/3/5.
//  Copyright © 2018年 Hyc. All rights reserved.
//

#import "LinePointDetailView.h"


#define kScreen_W [UIScreen mainScreen].bounds.size.width
#define kScreen_H [UIScreen mainScreen].bounds.size.height

static const NSInteger kVerPadding = 15;
static const NSInteger kHorPadding = 15;
static const NSInteger kLineH = 6;
static const NSInteger kPointHorSpacing = 45;
static const NSInteger kBtnWidth = kPointHorSpacing+5;
static const NSInteger kLineVerSpacing = 60;

@interface LinePointDetailView ()
//一行存放站点数
@property (nonatomic, assign) NSInteger lineMaxCount;
//补齐水平差值 horGap+kHorPadding ->X
@property (nonatomic, assign) CGFloat horGap;
//存放每个站点中心坐标
@property (nonatomic, strong) NSMutableArray *btnPointArray;
//存放模型
@property (nonatomic, strong) NSMutableArray *dataArray;
//分割线
@property (nonatomic, strong) BMLineView *lineView;
@property (nonatomic, assign) LinePointSetType setType;
@end
@implementation LinePointDetailView

+ (CGFloat)heightForLinePointViewWithPointCount:(NSInteger)count showBottonLine:(BOOL)isShow {
    if (count < 1) {
        return 0;
    }
    NSInteger lineMaxCount = (kScreen_W - kHorPadding*2 - kLineVerSpacing)/kPointHorSpacing;
    NSInteger lineCount = ceil(count*1.0 / lineMaxCount);
    
    CGFloat height = kVerPadding*2 + lineCount * kLineVerSpacing;
    if (isShow) {
        height += 10;
    }
    return height;
}

- (instancetype)initWithLineColor:(UIColor *)lineColor {
    if (self = [super init]) {
        self.backgroundColor = [UIColor whiteColor];
        _lineColor = lineColor;
        _lineMaxCount = (kScreen_W - kHorPadding*2 - kLineVerSpacing)/kPointHorSpacing;
        _horGap = (kScreen_W - kHorPadding*2 - kLineVerSpacing -_lineMaxCount * kPointHorSpacing)*0.5;
    }
    return self;
}

//- (instancetype)initWithFrame:(CGRect)frame {
//    if (self = [super initWithFrame:frame]) {
//        self.backgroundColor = [UIColor whiteColor];
//        _lineMaxCount = (kScreen_W - kHorPadding*2 - kLineVerSpacing)/kPointHorSpacing;
//        _horGap = (kScreen_W - kHorPadding*2 - kLineVerSpacing -_lineMaxCount * kPointHorSpacing)*0.5;
//    }
//    return self;
//}

- (void)drawRect:(CGRect)rect {
    
    if (self.dataArray.count < 1) {
        return;
    }
    
    //设置线条颜色
    [self.lineColor set];
    
    CGFloat startX = _horGap + kHorPadding + +kLineVerSpacing*0.5;
    CGFloat startY = kVerPadding + kLineVerSpacing * 0.5;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    path.lineWidth = kLineH;
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle = kCGLineCapRound;
    
    _btnPointArray = [NSMutableArray array];
    
    for (int i = 0; i < self.dataArray.count; ++i) {
        //当前处在第几条线上
        NSInteger currentLine = i/_lineMaxCount;
        NSInteger index = i%_lineMaxCount;
        
        if (index == 0) {
            //当转折时,将point移动到转折点
            CGFloat edgeX = 0;
            CGFloat edgeY = currentLine * kLineVerSpacing;
            if (currentLine%2 == 0) {
                edgeX = 0;
            }
            else {
                edgeX = _lineMaxCount * kPointHorSpacing;
            }
            CGPoint startPoint = CGPointMake(startX + edgeX, startY + edgeY);
            [path moveToPoint:startPoint];
        }
        
        if (currentLine%2 == 0) {
            if (index == 0 && i != 0) {
                //画左边圈
                CGPoint circlePoint = CGPointMake(startX+3, startY+kLineVerSpacing*(currentLine-0.5));
                [self drawSemicircle:path direction:YES radius:kLineVerSpacing*0.5 centerPoint:circlePoint];
            }
            
            //从左向右画线
            CGPoint linePoint = CGPointMake(startX+(kPointHorSpacing+kPointHorSpacing/_lineMaxCount)*index, startY + kLineVerSpacing*currentLine);
            [path addLineToPoint:linePoint];
            NSLog(@"index:%d,%@",i,NSStringFromCGPoint(linePoint));
            
            //处理y值 对齐
            [self.btnPointArray addObject:[NSValue valueWithCGPoint:linePoint]];
        }
        else {
            if (index == 0 && i != 0) {
                //画右边圈
                CGPoint circlePoint = CGPointMake(startX+_lineMaxCount*kPointHorSpacing-3, startY+kLineVerSpacing*(currentLine-0.5));
                [self drawSemicircle:path direction:NO radius:kLineVerSpacing*0.5 centerPoint:circlePoint];
                
                if (index == _lineMaxCount-1) {
                    index = _lineMaxCount;
                }
            }
            
            //从右向左画线
            CGPoint linePoint = CGPointMake(startX+_lineMaxCount*kPointHorSpacing-(kPointHorSpacing+kPointHorSpacing/_lineMaxCount)*index-4, startY + kLineVerSpacing*currentLine);
            [path addLineToPoint:linePoint];
            NSLog(@"index:%d,%@",i,NSStringFromCGPoint(linePoint));
            
            //处理y值 对齐
            [self.btnPointArray addObject:[NSValue valueWithCGPoint:linePoint]];
        }
    }
    
    [path stroke];
    
    if (self.setType == LinePointSetTypeLineDetailModel) {
        [self setupPointButton];
    }
    else if (self.setType == LinePointSetTypeStationArray) {
        [self setupPointButtonWithStationArray];
    }
    
}

- (void)drawSemicircle:(UIBezierPath *)path direction:(BOOL)isLeft radius:(NSInteger)radius centerPoint:(CGPoint)centerPoint{
    CGFloat startAngle = 0;
    CGFloat endAngle = 0;
    if (isLeft) {
        startAngle = 0.5*M_PI;
        endAngle = 1.5*M_PI;
    }
    else {
        startAngle = -0.5*M_PI;
        endAngle = 0.5*M_PI;
    }
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
    circlePath.lineWidth = kLineH;
    circlePath.lineCapStyle = kCGLineCapSquare;
    [circlePath stroke];
}


- (void)setupPointButton {
    [self removeAllSubviews];
    for (int i = 0; i < self.dataArray.count; ++i) {
        LinePointDetailType type = LinePointDetailTypeSection;
        NSString *title = @"";
        id obj = [self.dataArray objectAtIndex:i];
        if ([obj isKindOfClass:[LineStationModel class]]) {
            LineStationModel *stationModel = (LineStationModel *)obj;
            if (stationModel.isStart) {
                type = LinePointDetailTypeStart;
            }
            else if (stationModel.isEnd) {
                type = LinePointDetailTypeEnd;
            }
            else {
                type = LinePointDetailTypeStop;
            }
            title = stationModel.station_name;
        }
        else if ([obj isKindOfClass:[LineSectionModel class]]) {
            LineSectionModel *sectionModel = (LineSectionModel *)obj;
            if (sectionModel.isEnd) {
                type = LinePointDetailTypeSectionEnd;
            }
            else {
                type = LinePointDetailTypeSection;
            }
            
            title = sectionModel.section_name;
        }
        
        
        LinePointButton *button = [LinePointButton linePointSectionButtonWithTitle:title style:type];
        button.lineColor = self.lineColor;
        button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        button.tag = i;
        button.titleLabel.numberOfLines = 0;
        [self addSubview:button];
        [button setFrame:CGRectMake(0, 0, kBtnWidth, 50)];
        CGPoint buttonCenter = [[self.btnPointArray objectAtIndex:i] CGPointValue];
        buttonCenter.y += 15;
        button.center = buttonCenter;
        [button addTarget:self action:@selector(clickPointButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    self.showBottomLine = YES;
}

- (void)setupPointButtonWithStationArray {
    [self removeAllSubviews];
    for (int i = 0; i < self.dataArray.count; ++i) {
        LinePointDetailType type = LinePointDetailTypeSection;
        NSString *title = @"";
        BOOL isSelect = NO;
        id obj = [self.dataArray objectAtIndex:i];
        if ([obj isKindOfClass:[FactoryTreeStationModel class]]) {
            FactoryTreeStationModel *stationModel = (FactoryTreeStationModel *)obj;
            if (stationModel.isStart) {
                type = LinePointDetailTypeStart;
            }
            else if (stationModel.isEnd) {
                type = LinePointDetailTypeEnd;
            }
            else {
                type = LinePointDetailTypeStop;
            }
            title = stationModel.station_name;
            isSelect = stationModel.isSelect;
        }
        else if ([obj isKindOfClass:[FactoryTreeSectionModel class]]) {
            FactoryTreeSectionModel *sectionModel = (FactoryTreeSectionModel *)obj;
            if (sectionModel.isEnd) {
                type = LinePointDetailTypeSectionEnd;
            }
            else {
                type = LinePointDetailTypeSection;
            }
            title = sectionModel.section_name;
            isSelect = sectionModel.isSelect;
        }
        
        LinePointButton *button = [LinePointButton linePointSectionButtonWithTitle:title style:type];
        button.lineColor = self.lineColor;
        button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        button.tag = i;
        button.isSelect = isSelect;
        button.titleLabel.numberOfLines = 0;
        [self addSubview:button];
        [button setFrame:CGRectMake(0, 0, kBtnWidth, 50)];
        CGPoint buttonCenter = [[self.btnPointArray objectAtIndex:i] CGPointValue];
        buttonCenter.y += 15;
        button.center = buttonCenter;
        [button addTarget:self action:@selector(clickPointButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    self.showBottomLine = YES;
}

- (void)clickPointButton:(LinePointButton *)button {
    if (self.setType == LinePointSetTypeStationArray) {
        for (int i = 0; i < self.subviews.count; ++i) {
            LinePointButton *btn = [self.subviews objectAtIndex:i];
            if ([btn isKindOfClass:[LinePointButton class]]) {
                btn.isSelect = [btn isEqual:button];
            }
        }
    }
    
    id obj = [self.dataArray objectAtIndex:button.tag];
    if (self.BlockClickButton) {
        self.BlockClickButton(obj);
    }
}

#pragma mark - 线路管理
- (void)setLineDetailModel:(LineDetailModel *)lineDetailModel {
    _lineDetailModel = lineDetailModel;
    self.setType = LinePointSetTypeLineDetailModel;
    
    NSMutableArray *pointArray = [NSMutableArray array];
    
    NSMutableArray *stationArray = [NSMutableArray arrayWithArray:lineDetailModel.station_list];
    NSMutableArray *sectionArray = [NSMutableArray arrayWithArray:lineDetailModel.section_list];
 
    //站点排序
    for (int i = 0; i < stationArray.count; ++i) {
        for (int j = 0; j < stationArray.count-1-i; ++j) {
            LineStationModel *stationI = [stationArray objectAtIndex:j+1];
            LineStationModel *stationJ = [stationArray objectAtIndex:j];
            if ([stationI.station_num integerValue] < [stationJ.station_num integerValue]) {
                [stationArray exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
    
    //根据 站点(所属标段),站点(所属标段)排序
    for (int i = 0; i < stationArray.count; ++i) {
        LineStationModel *stationModel = [stationArray objectAtIndex:i];
        
        if (i == 0) {
            stationModel.isStart = YES;
        }
//        else if (i == stationArray.count-1) {
//            stationModel.isEnd = YES;
//        }
        
        //添加站点
        [pointArray addObject:stationModel];
        
        NSMutableArray *subArray = [NSMutableArray array];
        
        //获取站点对应的标段
        for (int k = 0; k < sectionArray.count; ++k) {
            LineSectionModel *sectionModel = [sectionArray objectAtIndex:k];
            if ([sectionModel.stationid isEqualToString:stationModel.stationid]) {
                [subArray addObject:sectionModel];
                if (i == stationArray.count-1 && k == sectionArray.count-1) {
                    sectionModel.isEnd = YES;
                }
            }
        }
        
        if (i == stationArray.count-1 && subArray.count == 0) {
            stationModel.isEnd = YES;
        }
        
        //排序
        for (int k = 0; k < subArray.count; ++k) {
            for (int j = 0; j < subArray.count-1-k; ++j) {
                LineSectionModel *sectionk = [subArray objectAtIndex:j+1];
                LineSectionModel *sectionj = [subArray objectAtIndex:j];
                if ([sectionk.section_num integerValue] < [sectionj.section_num integerValue]) {
                    [subArray exchangeObjectAtIndex:j withObjectAtIndex:j+1];
                }
            }
        }
        
        //添加站点对应的标段
        [pointArray addObjectsFromArray:subArray];
    }

    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, [[self class] heightForLinePointViewWithPointCount:pointArray.count showBottonLine:YES]);
    self.dataArray = pointArray;
}


#pragma mark - 选择工区
- (void)setStationArray:(NSArray<FactoryTreeStationModel *> *)stationArray {
    _stationArray = stationArray;
    self.setType = LinePointSetTypeStationArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    
    NSMutableArray *stationMtbArray = [NSMutableArray arrayWithArray:stationArray];
    
    //站点排序
    for (int i = 0; i < stationMtbArray.count; ++i) {
        for (int j = 0; j < stationMtbArray.count-1-i; ++j) {
            FactoryTreeStationModel *stationI = [stationMtbArray objectAtIndex:j+1];
            FactoryTreeStationModel *stationJ = [stationMtbArray objectAtIndex:j];
            if ([stationI.station_num integerValue] < [stationJ.station_num integerValue]) {
                [stationMtbArray exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
    
    //根据 站点(所属标段),站点(所属标段)排序
    for (int i = 0; i < stationArray.count; ++i) {
        FactoryTreeStationModel *stationModel = [stationMtbArray objectAtIndex:i];
        
        if (i == 0) {
            stationModel.isStart = YES;
        }
//        else if (i == stationArray.count-1) {
//            stationModel.isEnd = YES;
//        }
        
        NSMutableArray *sectionArray = [NSMutableArray arrayWithArray:stationModel.section_list];
        
        if (i == stationArray.count-1) {
            if (sectionArray.count > 0) {
                FactoryTreeSectionModel *section = [sectionArray lastObject];
                section.isEnd = YES;
            }
            else {
                stationModel.isEnd = YES;
            }
        }
        
        //添加站点
        [pointArray addObject:stationModel];
        
        //排序
        for (int k = 0; k < sectionArray.count; ++k) {
            for (int j = 0; j < sectionArray.count-1-k; ++j) {
                FactoryTreeSectionModel *sectionk = [sectionArray objectAtIndex:j+1];
                FactoryTreeSectionModel *sectionj = [sectionArray objectAtIndex:j];
                if ([sectionk.section_num integerValue] < [sectionj.section_num integerValue]) {
                    [sectionArray exchangeObjectAtIndex:j withObjectAtIndex:j+1];
                }
            }
        }
        
        //添加站点对应的标段
        [pointArray addObjectsFromArray:sectionArray];
    }
    
    //设置frame
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, [[self class] heightForLinePointViewWithPointCount:pointArray.count showBottonLine:YES]);
    
    //赋值
    self.dataArray = pointArray;
}

#pragma mark - setter
- (void)setDataArray:(NSMutableArray *)dataArray {
    _dataArray = dataArray;
    [self setNeedsDisplay];
}

- (void)setShowBottomLine:(BOOL)showBottomLine {
    _showBottomLine = showBottomLine;
    if (showBottomLine) {
        if (!self.lineView.superview) {
            [self addSubview:self.lineView];
            [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(self);
                make.height.mas_equalTo(10);
            }];
        }
    }
    else {
        if (self.lineView.superview) {
            [self.lineView removeFromSuperview];
        }
    }
}

#pragma mark - getter
- (BMLineView *)lineView {
    if (!_lineView) {
        _lineView = [BMLineView lineViewWithFrame:CGRectZero];
    }
    return _lineView;
}
@end
